package com.huakai.springenv.basic;

public class VolatileExample2 {
    private int x = 0;
    private int y = 0;

    public void thread1() {
        x = 1; // 指令A
        y = 2; // 指令B
    }

    public void thread2() {
        if (y == 2) { // 指令C
            // 读取x的值
            // System.out.println(x); // 指令D
            if (x == 0){
                System.err.println("x指为0错误.指令重排发生");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 1000000; i++) {
            VolatileExample2 example = new VolatileExample2();

            // 创建并启动线程1
            Thread t1 = new Thread(() -> example.thread1());
            // 创建并启动线程2
            Thread t2 = new Thread(() -> example.thread2());

            t1.start();
            t2.start();

            t1.join();
            t2.join();
        }
    }
}
